package com.szj.coroutine.project.jvm.blog5

import com.szj.coroutine.project.jvm.util.printlnThread
import kotlinx.coroutines.*
import kotlinx.coroutines.test.setMain
import kotlin.coroutines.*

/*
 * 作者: 史大拿
 * 时间: 2023/2/22$ 20:20$
 */
data class Test(val message: String)

suspend fun main() = runBlocking {
    val a = Test("我是测试数据")
    launch {

    }

    testSuspend(a) {
        delay(1000)
        coroutineContext
        printlnThread("test = $this")
        "我是返回值"
    }

    delay(2000)
}

private fun testSuspend(
    receiver: Test,
    block: suspend Test.() -> String
) {
    Dispatchers.setMain(Dispatchers.Unconfined)

    // 手动创建协程
    val continuation = block.createCoroutine(receiver, object : Continuation<String> {
        override val context: CoroutineContext
            get() = Dispatchers.Main

        override fun resumeWith(result: Result<String>) {
            println("result:${result.getOrNull()}")
        }
    })
    continuation.resume(Unit) // 恢复，不恢复无法工作
}